// pages/Goods/GoodsDes/index.js
var common = require('../../../public.js')
const config = require('../../../config.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isFyApp: config.isFyApp,
    itemId: '', //商品id
    title: '', //页面title
    shopData: [], //店铺数据
    Des: {}, //商品详情
    storeCouponsList: [], //店铺优惠券列表
    postMethodStr: '',
    storeId: '', //店铺Id
    attenyes: false, //店铺已关注
    attenno: true, //店铺关注
    property: false, //商品属性
    isVip: false,
    showVip: false,
    inviteCode: '',
    inputShowed: false,
    chackStep: 1,
    inviter: '', //邀请人信息
    code: '', // 用户vipcode
    commnet: '', // 评论对象
    commentType: '0', //评论类型 0=前两条  1=全部
    showComment: false,
    commentPlaceHolder: '我来说几句',
    commentValue: '',
    showGoodsParam: false, // 商品参数
    showIndemnity: false, // 消保面板
    showStoreCoupons: false, //店铺优惠券面板
    inputFocus: false,
    addCartPopup: false,
    goodsCount: 1,
    image: null,
    sellPoint: null,
    isLoadingBusy: false,
    favoriteGoodsFlag: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    this.setData({
      isLoadingBusy: true
    })
    var that = this;
    that.setData({
      itemId: opt.id,
      //itemId:'7887', // 测试 7887 惠民商品
      title: opt.name,
      isVip: opt.isVip ? true : false,
      image: opt.image ? opt.image : null,
      sellPoint: opt.sellPoint ? opt.sellPoint : null
    })
    wx.setNavigationBarTitle({
      title: that.data.title, //页面标题为路由参数
    })
    common.getLocalUserInfo(function (success, data) {
      if (success) {
        that.setData({
          userInfo: data.user,
          token: data.token,
          openid: data.openid
          // itemId: that.options.id,
        })
        that.getDataDes() //查询商品详情信息
        that.getartists() //判断是否是守艺人
        that.getgoodsArrtention() //判断商品是否收藏
        that.getGoodsCommentList() // 获取商品评论
      }
    }, true)
  },
  //判断是否是守艺人
  getartists: function () {
    var that = this
    var tempJson = {
      token: that.data.token,
      userId: that.data.userInfo.id
    };
    common.post("/isPromoter", tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          code: res.data || ''
        })
      }
    })
  },
  toStore() { //跳转店铺
    const storeType = this.data.shopData.storeType
    if (storeType == 6) {
      wx.navigateTo({
        url: '/pages/ScenicArea/ScenicAreaMainPage/index?id=' + this.data.shopData.id + '&moduleType=1',
      })
    } else if (storeType == 1 || storeType == 24 || storeType == 23) {
      wx.navigateTo({
        url: '/pages/ScenicArea/ScenicAreaMainPage/index?id=' + this.data.shopData.id + '&moduleType=2',
      })
    } else {
      common.gotoStore(this.data.shopData)
    }
  },
  focusInput() {
    this.setData({
      inputShowed: true
    })
  },
  changeCode(e) {
    this.setData({
      inviteCode: e.detail.value
    })
  },
  getInviteCode() {
    let that = this
    if (that.data.inviteCode.length < 6) {
      common.showToast('请填写正确的邀请码')
      return false
    }
    let tempJson = {
      inviteCode: that.data.inviteCode,
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.post("/getPromoterInfo", tempJson, function (res) {
      if (res.status == 200) {
        that.setData({
          inviter: res.data,
          chackStep: 2
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  onClose() {
    this.setData({
      showVip: false,
      chackStep: 1,
      inviteCode: ""
    })
  },
  getStoreCoupons(storeId) {
    const that = this
    const params = {
      storeId: storeId,
      pageNum: 1,
      status: 4
    }
    common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
      if (res.status === 200) {
        that.setData({
          storeCouponsList: res.data.result_list
        })
      }
    })
  },
  //查看是否关注店铺
  // getshopArrtention: function () {
  //   var that = this
  //   var tempJson = {
  //     token: that.data.token,
  //     userId: that.data.userInfo.id,
  //     storeId: that.data.storeId
  //   };
  //   common.post("/store/favo/collected", tempJson, function (res) {
  //     if (res.status == 200) {
  //       that.setData({
  //         attenyes: true,
  //         attenno: false
  //       })
  //     } else {
  //       that.setData({
  //         attenyes: false,
  //         attenno: true
  //       })
  //     }
  //   });
  // },
  //查询是否收藏商品状态
  getgoodsArrtention: function () {
    const that = this
    const tempJson = {
      token: that.data.token,
      userId: that.data.userInfo.id,
      itemId: that.data.itemId
    }
    common.post("/item/favo/collected", tempJson, function (res) {
      if (res.status == 200) {
        that.setData({
          favoriteGoodsFlag: true
        })
      } else {
        that.setData({
          favoriteGoodsFlag: false
        })
      }
    })
  },
  //关注该店铺
  // attention_no: function () {
  //   var that = this
  //   var tempJson = {
  //     token: that.data.token,
  //     userId: that.data.userInfo.id,
  //     storeId: that.data.storeId
  //   };
  //   common.wxRequest("/store/favo/add", "get", tempJson, 'application/json', function (res) {
  //     if (res.status == 200) {
  //       that.setData({
  //         attenyes: true,
  //         attenno: false
  //       })
  //       wx.showToast({
  //         title: '已关注',
  //         icon: 'none'
  //       })
  //     } else {
  //       wx.showToast({
  //         title: '关注失败',
  //         icon: 'none'
  //       })
  //     }
  //   });
  // },
  //取消收藏该商品
  favoriteGoods(collect) {
    const that = this
    const tempJson = {
      token: that.data.token,
      userId: that.data.userInfo.id,
      itemId: that.data.itemId
    }
    const url = collect ? '/item/favo/add' : '/item/favo/delete'
    common.post(url, tempJson, function (res) {
      if (res.status == 200) {
        that.setData({
          favoriteGoodsFlag: collect
        })
        common.showToast(collect ? '已收藏' : '已取消收藏')
      } else {
        common.showToast(collect ? '收藏失败' : '取消失败')
      }
    })
  },
  //取消关注该店铺
  attention_yes: function () {
    var that = this
    var tempJson = {
      token: that.data.token,
      userId: that.data.userInfo.id,
      storeId: that.data.storeId
    };
    common.wxRequest("/store/favo/delete", "get", tempJson, 'application/json', function (res) {
      if (res.status == 200) {
        that.setData({
          attenyes: false,
          attenno: true
        })
        wx.showToast({
          title: '已取消关注',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '取消失败',
          icon: 'none'
        })
      }
    });
  },
  //查询商品详情信息
  getDataDes: function () {
    var that = this
    var tempJson = {
      itemId: that.data.itemId,
      // itemId:8102
      // itemId:8313
    }
    common.post("/item/info", tempJson, function (res) {
      if (res.status === 200) {
        //itemAttrList没有数据隐藏商品属性模块 有数据显示遍历
        if (res.data.itemAttrList.length == 0) {
          that.setData({
            property: true
          })
        } else {
          that.setData({
            property: false,
            itemAttrList: res.data.itemAttrList,
            image: res.data.image,
            title: res.data.title
          })
        }
        const richText = res.data.itemDesc ? res.data.itemDesc.replace(/\<img/gi, '<img class="rich-img" ') : ''
        that.setData({
          Des: res.data,
          title: res.data.title,
          storeId: res.data.storeId,
          goodsInformation: richText,
          sellPoint: res.data.sellPoint
        }, function () {
          that.getShopDes(); //店铺信息
          that.getPostMethod(); // 获取配送方式
          // that.getshopArrtention(); //是否关注店铺
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        isLoadingBusy: false
      })
    })
  },
  //查询店铺详情信息
  getShopDes: function () {
    const that = this
    const tempJson = {
      storeId: that.data.storeId
    }
    common.post("/store/info", tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          shopData: res.data,
        }, function () {
          that.getStoreCoupons(res.data.id)
        })
      }
    })
  },
  receiveStoreConpons(e) {
    let that = this
    let {
      couponid
    } = e.currentTarget.dataset
    let tempJson = {
      userId: that.data.userInfo.id,
      discountCouponId: couponid,
      source: 1, // 1为手动领取，2为系统群发
      token: that.data.token
    }
    common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
      if (res.status == 200) {
        wx.showToast({
          title: '领取成功',
          icon: "none"
        })
      } else {
        wx.showToast({
          title: res.msg ? res.msg : '领取失败',
          icon: "none"
        })
      }
    })
  },
  // 点击购买vip商品
  buyVipGoods() {
    let that = this
    wx.navigateTo({
      url: '/pages/Goods/Commit/index?itemId=' + that.data.Des.id + '&storeId=' + that.data.storeId + '&invitationCode=' + that.data.inviteCode,
    })
  },
  purchase() {
    var that = this
    console.log('vip1', that.data.isVip)
    console.log('vip2', that.data.code)
    if (that.data.isVip && that.data.code == '') { // 是vip商品且用户不是手艺人
      that.setData({
        showVip: true
      })
    } else {
      wx.navigateTo({
        url: '../Commit/index?itemId=' + that.data.Des.id + '&storeId=' + that.data.storeId,
      })
    }
  },
  goBack() {
    wx.navigateBack({
      url: '../../index/index'
    })
  },
  comeInClick() {
    const pages = getCurrentPages()
    wx.navigateBack({
      delta: pages.length
    })
  },
  getPostMethod() {
    var that = this
    var tempJson = {
      storeId: that.data.storeId
    };
    common.post("/store/getPostTypeNew", tempJson, function (res) {
      if (res.status === 200) {
        let postType = []
        res.data.map(item => {
          postType.push(item.dname)
        })
        that.setData({
          postMethodStr: postType.join(' | ')
        })
      }
    })
  },
  // gotoCart() {
  //   wx.redirectTo({
  //     url: '/pages/ShoppingCart/index',
  //   })
  // },
  collectionAction() {
    if (this.data.favoriteGoodsFlag) {
      this.favoriteGoods(false)
    } else {
      this.favoriteGoods(true)
    }
  },
  //获取评论列表
  getGoodsCommentList() {
    var that = this
    var tempJson = {
      itemId: that.data.itemId,
      pageNum: '',
      type: that.data.commentType, //0标识取前2条   1全部数据
      userId: that.data.userInfo.id
    };
    common.post("/comment/getItemCommentlist", tempJson, function (res) {
      console.log(res)
      that.setData({
        commnet: res.data
      })

    })
  },
  //点击回复
  clickRely(e) {
    let {
      item
    } = e.currentTarget.dataset
    let that = this
    console.log(item)
    this.setData({
      showComment: true,
      commentPlaceHolder: '@' + item.alias + ':',
      commentId: item.id
    }, _ => {
      setTimeout(function () {
        that.setData({
          inputFocus: true
        })
      }, 500)
    })
  },
  //输入评论
  changeCommnet(e) {
    console.log(e)
    let {
      value
    } = e.detail
    this.setData({
      commentValue: value
    })
  },
  saveComment() {
    if (this.data.commentValue === null || this.data.commentValue.length === 0) {
      wx.showToast({
        icon: 'none',
        title: '您没有输入任何文字',
      })
      return
    }
    const that = this
    wx.cloud.callFunction({
      name: 'ContentCheck',
      data: {
        txt: that.data.commentValue
      },
      success(res) {
        if (res.result.errCode == 87014) {
          console.log(res.errCode)
          wx.showToast({
            icon: 'none',
            title: '文字违规，请重新输入',
          })
        } else {
          // 合规
          let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            commentId: that.data.commentId,
            content: that.data.commentValue
          }
          common.post('/comment/saveItemCommentChat', tempJson, function (res) {
            console.log(res)
            if (res.status == 200) {
              that.onCommentClose()
              that.getGoodsCommentList()
              wx.showToast({
                title: '评论成功',
              })
            } else {
              common.showRequestErrMsg(res)
            }
          })
        }
      },
      fail(err) {
        wx.showToast({
          icon: 'none',
          title: '文字违规，请重新输入',
        })
      }
    })
  },
  OpenStoreCouponos() {
    this.setData({
      showStoreCoupons: true
    })
  },
  onStoreCouponosClose() {
    this.setData({
      showStoreCoupons: false
    })
  },
  OpenGoodsParam() {
    this.setData({
      showGoodsParam: true
    })
  },
  closeGoodsParam() {
    this.setData({
      showGoodsParam: false
    })
  },
  OpenIndemnity() {
    this.setData({
      showIndemnity: true
    })
  },
  closeIndemnity() {
    this.setData({
      showIndemnity: false
    })
  },
  onCommentClose() { // 关闭模态框
    console.log('666')
    this.setData({
      commentId: ' ',
      commentValue: ' ',
      showComment: false,
    })
  },
  commentPraise(e) { //点赞
    console.log(e.currentTarget.dataset)
    let {
      id
    } = e.currentTarget.dataset
    let that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      commnetId: id
    }
    common.post('/comment/saveCommentPraise', tempJson, function (res) {
      console.log(res)
      if (res.status == 200) {
        that.getGoodsCommentList()
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  //取消点赞
  cancleCommentPraise(id) {
    let that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      commnetId: id
    }
    common.post("/comment/cancleCommentPraise", tempJson, function (res) {
      if (res.status === 200) {
        that.getGoodsCommentList()
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  //获取全部列表
  getAllComment() {
    wx.navigateTo({
      url: '/pages/Goods/Comment/index?itemId=' + this.data.itemId,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.title,
      path: 'pages/Goods/GoodsDes/index?id=' + this.data.itemId,
      // imageUrl: '/images/home.png',
      success: (res) => {
        // 分享成功
      },
      fail: (res) => {
        // 分享失败
      }
    }
  },
  addCart() { },
  showAddCart() {
    this.setData({
      addCartPopup: true
    })
  },
  closeAddCart() {
    this.setData({
      addCartPopup: false
    })
  },
  onNumChange(e) {
    const count = e.currentTarget.detail
    this.setData({
      goodsCount: count
    })
  },
  submitAddCart() {
    const that = this
    const num = this.data.goodsCount
    const itemId = this.data.itemId
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      itemId,
      num
    }
    common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
      if (res.status === 200) {
        that.closeAddCart()
        wx.showToast({
          title: '添加成功!',
        })
      } else {
        wx.showToast({
          title: res.msg ? res.msg : '添加失败',
        })
      }
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.shopData.mobile,
      fail: function (res) { }
    })
  }
})